package com.example.administrator.base.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Gradient;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolygonOptions;
import com.example.administrator.base.R;
import com.example.administrator.base.baseActivity.BaseActivity;
import com.example.administrator.base.bean.AllStatusCountxBean;
import com.example.administrator.base.bean.PointReqBean;
import com.example.administrator.base.bean.SingleBicycle;
import com.example.administrator.base.util.ChangeLatToLon;
import com.example.administrator.base.util.GsonTools;
import com.example.administrator.base.util.NoToName;
import com.example.administrator.base.util.SharedPreferencesUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SerchCar extends BaseActivity {
    @InjectView(R.id.Toolbar)
    android.support.v7.widget.Toolbar Toolbar;

    @InjectView(R.id.tv_name)
    TextView tvName;
    @InjectView(R.id.tv_lasttime)
    TextView tvLasttime;
    @InjectView(R.id.tv_speed)
    TextView tvSpeed;
    @InjectView(R.id.tv_city)
    TextView tvCity;
    @InjectView(R.id.tv_stutes)
    TextView tvStutes;
    SweetAlertDialog sweetAlertDialog;
    List<LatLng> latLngs;
    List<Marker> overlays;
    String pointlist = "";
    String newpointlist = "";
    Intent intent;
    String city, point;
    double lat, lng;

    @InjectView(R.id.linearLayout)
    LinearLayout linearLayout;
    @InjectView(R.id.tv_unrechargeable_Bike)
    TextView mTvUnrechargeableBike;
    @InjectView(R.id.tv_needback)
    TextView tvNeedback;
    @InjectView(R.id.map)
    MapView map;
    @InjectView(R.id.tv_repairing)
    TextView tvRepairing;
    @InjectView(R.id.tv_shutdown)
    TextView tvShutdown;
    private List<MarkerOptions> MarkerList;
    private String urlall = "http://yingyan.baidu.com/api/v3/entity/polygonsearch";
    private BitmapDescriptor bicycleBitmap1, bicycleBitmap2, bicycleBitmap3, bicycleBitmap4, bicycleBitmap5, bicycleBitmap6, bicycleBitmap7, bicycleBitmap8, bicycleBitmap9, bicycleBitmap10, bicycleBitmap11, bicycleBitmap16, bicycleBitmap17,bicycleBitmap18;
    Gradient gradient;
    private AllStatusCountxBean mMsg;
    public CoordinateConverter converter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serch_car);
        ButterKnife.inject(this);
        map.onCreate(savedInstanceState);
        int[] DEFAULT_GRADIENT_COLORS = {Color.rgb(0, 201, 87), Color.rgb(255, 0, 0)};
        float[] DEFAULT_GRADIENT_START_POINTS = {0.05f, 0.1f};
        gradient = new Gradient(DEFAULT_GRADIENT_COLORS, DEFAULT_GRADIENT_START_POINTS);
        city = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "city", ""));
        point = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "position", ""));
        lat = Double.parseDouble(String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "latitude", "")));
        lng = Double.parseDouble(String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "longtitude", "")));
        latLngs = new ArrayList<>();
        Toolbar.setTitle("赳猎人");
        Toolbar.setSubtitle("查找车辆");
        setSupportActionBar(Toolbar);
        Toolbar.setNavigationIcon(R.drawable.backbar);
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setCanceledOnTouchOutside(false);
        sweetAlertDialog.setTitleText("加载中");
        MarkerList = new ArrayList<>();
        overlays = new ArrayList<>();
        intent = getIntent();
        converter = new CoordinateConverter(this);
        converter.from(CoordinateConverter.CoordType.BAIDU);
        String number = intent.getStringExtra("car");
        bicycleBitmap1 = BitmapDescriptorFactory.fromResource(R.drawable.o1);
        bicycleBitmap2 = BitmapDescriptorFactory.fromResource(R.drawable.o3);
        bicycleBitmap3 = BitmapDescriptorFactory.fromResource(R.drawable.o5);
        bicycleBitmap4 = BitmapDescriptorFactory.fromResource(R.drawable.o8);
        bicycleBitmap5 = BitmapDescriptorFactory.fromResource(R.drawable.o4); //维修中
        bicycleBitmap6 = BitmapDescriptorFactory.fromResource(R.drawable.o2);//未绑定
        bicycleBitmap7 = BitmapDescriptorFactory.fromResource(R.drawable.o6);// 不可充电
        bicycleBitmap8 = BitmapDescriptorFactory.fromResource(R.drawable.o7);
        bicycleBitmap9 = BitmapDescriptorFactory.fromResource(R.drawable.o11);
        bicycleBitmap10 = BitmapDescriptorFactory.fromResource(R.drawable.o12);
        bicycleBitmap11 = BitmapDescriptorFactory.fromResource(R.drawable.o13);//围栏外
        bicycleBitmap16 = BitmapDescriptorFactory.fromResource(R.drawable.o14);
        bicycleBitmap17 = BitmapDescriptorFactory.fromResource(R.drawable.o15);
        bicycleBitmap18 = BitmapDescriptorFactory.fromResource(R.drawable.o18);
        if (number != null) {
            sweetAlertDialog.show();
            GetBicycle(number);
        } else {
            String type = intent.getStringExtra("type");

            if (type.equals("serchallcar")) {
                if (!point.equals("")) {
                    Log.i("23220155", "xx" + point);
                    String[] point1 = point.split("\\||,");
                    int y = point1.length;

                    for (int i = 0; i < y; i += 2) {
                        LatLng latLng = new LatLng(Double.parseDouble(point1[i + 1]), Double.parseDouble(point1[i]));
                        converter.coord(latLng);
                        LatLng desLatLng = converter.convert();
                        latLngs.add(desLatLng);
                    }
                    setPolygon();
                    resetnewLocation(latLngs);
                    String syscode = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "sysCode", ""));
                    Log.i("2125845", "" + syscode);
                    if (syscode.equals("5")) {
                        String mCityNo = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "areaId", ""));
                        String mAdminId = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "adminId", ""));
                        getAllStatusCount(mCityNo, mAdminId);
                    } else {
                        String[] split = point.split("\\|");
                        for (String aSplit : split) {
                            String latLon = ChangeLatToLon.LatLon(aSplit);
                            pointlist = pointlist + latLon + ";";
                        }
                        newpointlist = pointlist.substring(0, pointlist.length() - 1);
                        IsOverArea(newpointlist);
                    }
                }
            }

            if (type.equals("low")) {

                if (!city.equals("")) {
                    if (!point.equals("")) {
                        String[] point1 = point.split("\\||,");
                        int y = point1.length;
                        drawlocation();
                        resetLocation(lat, lng, 15);
                        for (int i = 0; i < y; i += 2) {
                            LatLng latLng = new LatLng(Double.parseDouble(point1[i + 1]), Double.parseDouble(point1[i]));
                            converter.coord(latLng);
                            LatLng desLatLng = converter.convert();
                            latLngs.add(desLatLng);
                        }
                        setPolygon();
                    }
                    String cityNo = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "cityNo", ""));
                    GetBadBicycle("8", city, cityNo);
                }
            }

            if (type.equals("zombie")) {

                if (!city.equals("")) {
                    if (!point.equals("")) {
                        String[] point1 = point.split("\\||,");
                        int y = point1.length;
                        drawlocation();
                        resetLocation(lat, lng, 15);
                        for (int i = 0; i < y; i += 2) {
                            LatLng latLng = new LatLng(Double.parseDouble(point1[i + 1]), Double.parseDouble(point1[i]));
                            converter.coord(latLng);
                            LatLng desLatLng = converter.convert();
                            latLngs.add(desLatLng);
                        }
                        setPolygon();
                    }
                    String cityNo = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "cityNo", ""));
                    GetBadBicycle("2", city, cityNo);
                }

            }

            if (type.equals("break")) {

                if (!city.equals("")) {
                    if (!point.equals("")) {
                        String[] point1 = point.split("\\||,");
                        int y = point1.length;
                        drawlocation();
                        resetLocation(lat, lng, 15);
                        for (int i = 0; i < y; i += 2) {
                            LatLng latLng = new LatLng(Double.parseDouble(point1[i + 1]), Double.parseDouble(point1[i]));
                            converter.coord(latLng);
                            LatLng desLatLng = converter.convert();
                            latLngs.add(desLatLng);
                        }
                        setPolygon();
                    }
                    String cityNo = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "cityNo", ""));
                    GetBadBicycle("7", city, cityNo);
                }
            }

        }
    }

    /*数据库获取车辆数量*/
    private void getAllStatusCount(String areaId, String adminId) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "GETALLSTATUSCOUNT")
                .add("adminId", adminId)
                .add("cityNo", areaId)
                .build();
        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/operationperson?")
                .post(formBody)
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.i("21021310", "" + string);
                        mMsg = GsonTools.changeGsonToBean(string, AllStatusCountxBean.class);
                        if (mMsg == null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showToast("数据异常请重试");
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mMsg.getCode() == 1) {
                                        //数据请求成功
                                        tvName.setText("正常车数量：" + mMsg.getAllStatusCount().getCountNormalBike() + "辆");
                                        tvLasttime.setText("离线车数量：" + mMsg.getAllStatusCount().getCountOffLineBike() + "辆");
                                        tvSpeed.setText("故障车数量：" + mMsg.getAllStatusCount().getCountFaultBike() + "辆");
                                        tvCity.setText("低电量车数量：" + mMsg.getAllStatusCount().getCountLowBatteryBike() + "辆");
                                        tvStutes.setText("僵尸车数量：" + mMsg.getAllStatusCount().getCountCorpseStatusBike() + "辆");
                                        mTvUnrechargeableBike.setText("不可充电车:" + mMsg.getAllStatusCount().getCountUnrechargeableBike() + "辆");
                                        tvNeedback.setText("需召回车辆：" + mMsg.getAllStatusCount().getCountRecallStatusBike() + "辆");
                                        tvRepairing.setText("维修中车辆：" + mMsg.getAllStatusCount().getCountRepairingStatusBike() + "辆");
                                        tvShutdown.setText("关机车辆："+mMsg.getAllStatusCount().getCountShutdownBike()+"辆");
                                    } else {
                                        //数据请求失败
                                        showToast(mMsg.getMessage());
                                    }
                                }
                            });
                        }
                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /*绘制定位点*/
    public void drawlocation() {
        LatLng point = new LatLng(lat, lng);
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.me);
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(point);
        markerOption.icon(bitmap);
        markerOption.title("我的位置");
        markerOption.setFlat(true);
        markerOption.zIndex(9);
        map.getMap().addMarker(markerOption);
    }

    /*获取异常状态车位置*/
    public void GetBadBicycle(final String type, String city, String cityno) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
//创建一个Request
        final Request request = new Request.Builder()
                .url("http://yingyan.baidu.com/api/v3/entity/districtsearch" + "?ak=IK5AlGXoZ23tDAGjldRalicbhdpsrKwE&service_id=135958&coord_type_output=gcj02&keyword=" + city + "&filter=status:" + type + "|cityNo:" + cityno + "&page_size=1000")
                .build();
//new call
        Call call = mOkHttpClient.newCall(request);
//请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body().string();
                Log.i("33782156325432545", resp);
                final PointReqBean pointReqBean = GsonTools.changeGsonToBean(resp, PointReqBean.class);
                if (pointReqBean == null) {
                    Log.i("3378", "失败");
                } else {
                    if (!pointReqBean.getStatus().equals("0")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showToast("该区域没有目标车辆");
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int i = pointReqBean.getEntities().size();
                                Log.i("1455456", "" + i);
                                for (int x = 0; x < i; x++) {
                                    Log.i("1455456", "" + x);
                                    final double latitude = Double.parseDouble(pointReqBean.getEntities().get(x).getLatest_location().getLatitude());
                                    final double longitude = Double.parseDouble(pointReqBean.getEntities().get(x).getLatest_location().getLongitude());
                                    final String state = pointReqBean.getEntities().get(x).getStatus();
                                    Log.i("521545121585451", "" + state);

                                    if (null != state) {
                                        switch (state) {
                                            case "2":
                                                MarkerList.add(new MarkerOptions().icon(bicycleBitmap3).position(new LatLng(latitude, longitude)).zIndex(1));

                                                break;
                                            case "7":
                                                MarkerList.add(new MarkerOptions().icon(bicycleBitmap8).position(new LatLng(latitude, longitude)).zIndex(1));
                                                break;

                                            case "8":
                                                MarkerList.add(new MarkerOptions().icon(bicycleBitmap9).position(new LatLng(latitude, longitude)).zIndex(1));
                                                break;
                                        }
                                    }

                                }
                                overlays = map.getMap().addMarkers((ArrayList<MarkerOptions>) MarkerList, true);
                                if (type.equals("2")) {
                                    tvName.setText(getString(R.string.offlinecarnumber, pointReqBean.getTotal()));
                                    tvLasttime.setText(getString(R.string.offlinecarshownumber, pointReqBean.getSize()));
                                    tvSpeed.setText("");
                                    tvCity.setText("");
                                    tvStutes.setText("");
                                    mTvUnrechargeableBike.setText("");
                                    tvNeedback.setText("");
                                    tvRepairing.setText("");
                                    tvShutdown.setText("");
                                }
                                if (type.equals("7")) {
                                    tvName.setText(getString(R.string.brokencarnumber, pointReqBean.getTotal()));
                                    tvLasttime.setText(getString(R.string.brokencarshownumber, pointReqBean.getSize()));
                                    tvSpeed.setText("");
                                    tvCity.setText("");
                                    tvStutes.setText("");
                                    mTvUnrechargeableBike.setText("");
                                    tvNeedback.setText("");
                                    tvRepairing.setText("");
                                    tvShutdown.setText("");
                                }
                                if (type.equals("8")) {
                                    tvName.setText(getString(R.string.lowpowercarnumber, pointReqBean.getTotal()));
                                    tvLasttime.setText(getString(R.string.lowpowercarshownumber, pointReqBean.getSize()));
                                    tvSpeed.setText("");
                                    tvCity.setText("");
                                    tvStutes.setText("");
                                    mTvUnrechargeableBike.setText("");
                                    tvNeedback.setText("");
                                    tvRepairing.setText("");
                                    tvShutdown.setText("");
                                }
                            }
                        });

                    }
                }
            }
        });
    }

    /*获取单车位置*/
    public void GetBicycle(String number) {
        String url = "http://yingyan.baidu.com/api/v3/entity/search";
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url + "?ak=IK5AlGXoZ23tDAGjldRalicbhdpsrKwE&service_id=135958&filter=entity_names:" + number + "&page_size=1000&coord_type_output=gcj02")
                .build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body().string();
                Log.i("1564151", resp);
                final SingleBicycle singleBicycle = GsonTools.changeGsonToBean(resp, SingleBicycle.class);
                if (singleBicycle != null) {
                    if (singleBicycle.getStatus() == 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                double lat = singleBicycle.getEntities().get(0).getLatest_location().getLatitude();
                                double lon = singleBicycle.getEntities().get(0).getLatest_location().getLongitude();
                                resetLocation(lat, lon, 20);
                                String name = singleBicycle.getEntities().get(0).getEntity_name();
                                double speed = singleBicycle.getEntities().get(0).getLatest_location().getSpeed();
                                String city = singleBicycle.getEntities().get(0).getCityNo();
                                String status = singleBicycle.getEntities().get(0).getStatus();
                                tvName.setText("");
                                String numberToName = NoToName.numberToName(SerchCar.this, Integer.parseInt(city));
                                tvCity.setText(getString(R.string.citynumber, numberToName));
                                tvLasttime.setText(getString(R.string.carnumber, name));
                                tvSpeed.setText(getString(R.string.speed, speed));
                                mTvUnrechargeableBike.setText("");
                                tvNeedback.setText("");
                                tvRepairing.setText("");
                                tvShutdown.setText("");
                            /*（0：正常 1：使用中  2:离线 3:报废 4:升级 5：预约中 6:借车处理中 7：故障    8：低电量车 ）*/
                                if (status != null) {
                                    switch (status) {
                                        case "0":
                                            tvStutes.setText("车辆状态：正常");
                                            setMarker(lat, lon, bicycleBitmap1);
                                            break;
                                        case "1":
                                            tvStutes.setText("车辆状态：使用中");
                                            setMarker(lat, lon, bicycleBitmap2);
                                            break;
                                        case "2":
                                            tvStutes.setText("车辆状态：离线");
                                            setMarker(lat, lon, bicycleBitmap3);
                                            break;
                                        case "3":
                                            tvStutes.setText("车辆状态：报废");
                                            setMarker(lat, lon, bicycleBitmap4);
                                            break;
                                        case "4":
                                            tvStutes.setText("车辆状态：升级");
                                            setMarker(lat, lon, bicycleBitmap5);
                                            break;
                                        case "5":
                                            tvStutes.setText("车辆状态：预约中");
                                            setMarker(lat, lon, bicycleBitmap6);
                                            break;
                                        case "6":
                                            tvStutes.setText("车辆状态：借车处理中");
                                            setMarker(lat, lon, bicycleBitmap7);
                                            break;
                                        case "7":
                                            tvStutes.setText("车辆状态：故障");
                                            setMarker(lat, lon, bicycleBitmap8);
                                            break;
                                        case "8":
                                            tvStutes.setText("车辆状态：低电量");
                                            setMarker(lat, lon, bicycleBitmap9);
                                            break;
                                        case "9":
                                            tvStutes.setText("车辆状态：僵尸车");
                                            setMarker(lat, lon, bicycleBitmap10);
                                            break;
                                        case "10":
                                            tvStutes.setText("车辆状态：不可充电");
                                            setMarker(lat, lon, bicycleBitmap7);
                                            break;
                                        case "11":
                                            tvStutes.setText("车辆状态：维修中");
                                            setMarker(lat, lon, bicycleBitmap5);
                                            break;
                                        case "12":
                                            tvStutes.setText("车辆状态：未绑定");
                                            setMarker(lat, lon, bicycleBitmap6);
                                            break;
                                        case "13":
                                            tvStutes.setText("车辆状态：电子围栏外");
                                            setMarker(lat, lon, bicycleBitmap11);
                                            break;
                                        case "14":
                                            tvStutes.setText("车辆状态：用户报故障车");
                                            setMarker(lat, lon, bicycleBitmap16);
                                            break;
                                        case "15":
                                            tvStutes.setText("车辆状态：需召回车辆");
                                            setMarker(lat, lon, bicycleBitmap17);
                                            break;
                                        case "16":
                                            tvStutes.setText("车辆状态：关机车");
                                            setMarker(lat, lon, bicycleBitmap18);
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                sweetAlertDialog.dismiss();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sweetAlertDialog.dismiss();
                                showToast("找不到该车");
                                finish();
                            }
                        });

                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast("获取数据失败");
                            sweetAlertDialog.dismiss();
                        }
                    });
                }

            }
        });
    }

    /*获取辖区单车数量    区域3000平方千米以内*/
    public void GetAllBicycle(String point, final String stutas, String cityno) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(urlall + "?ak=IK5AlGXoZ23tDAGjldRalicbhdpsrKwE&service_id=135958&vertexes=" + point + "&filter=status:" + stutas + "|cityNo:" + cityno + "&page_size=1")
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body().string();
                Log.i("15641511", resp);
                final SingleBicycle singleBicycle = GsonTools.changeGsonToBean(resp, SingleBicycle.class);
                if (singleBicycle != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (singleBicycle.getStatus() == 0) {
                                switch (stutas) {
                                 /*（0：正常 1：使用中  2:离线 3:报废 4:升级 5：预约中 6:借车处理中 7：故障    8：低电量车 ）*/
                                    case "0":
                                        tvName.setText("正常车数量：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "2":
                                        tvLasttime.setText("离线车数量：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "7":
                                        tvSpeed.setText("故障车数量：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "8":
                                        tvCity.setText("低电量车数量：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "9":
                                        tvStutes.setText("僵尸车数量：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "10":
                                        mTvUnrechargeableBike.setText("不可充电车：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "11":
                                        tvRepairing.setText("维修中车数量："+singleBicycle.getTotal()+"辆");
                                        break;
                                    case "15":
                                        tvNeedback.setText("需召回车辆：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "16":
                                        tvShutdown.setText("关机车：" + singleBicycle.getTotal() + "辆");
                                        break;
                                }
                            } else if (singleBicycle.getStatus() == 3003) {
                                switch (stutas) {
                                 /*（0：正常 1：使用中  2:离线 3:报废 4:升级 5：预约中 6:借车处理中 7：故障    8：低电量车 ）*/
                                    case "0":
                                        tvName.setText("正常车数量：0辆");
                                        break;
                                    case "2":
                                        tvLasttime.setText("离线车数量：0辆");
                                        break;
                                    case "7":
                                        tvSpeed.setText("故障车数量：0辆");
                                        break;
                                    case "8":
                                        tvCity.setText("低电量车数量：0辆");
                                        break;
                                    case "9":
                                        tvStutes.setText("僵尸车数量：0辆");
                                        break;
                                    case "10":
                                        mTvUnrechargeableBike.setText("不可充电车：0辆");
                                        break;
                                    case "11":
                                        tvRepairing.setText("维修中车数量：0辆");
                                        break;
                                    case "15":
                                        tvNeedback.setText("需召回车辆：0辆");
                                        break;
                                    case "16":
                                        tvShutdown.setText("关机车：0辆");
                                        break;
                                }
                            } else {
                                showToast("获取数据失败，请重试");
                            }

                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                        }
                    });
                }

            }
        });
    }


    /*获取辖区单车数量    区域3000平方千米以外*/
    public void GetAllBicycleErr(String location, final String stutas, String cityno) {
        String urlallerr = "http://yingyan.baidu.com/api/v3/entity/districtsearch";
        OkHttpClient mOkHttpClient = new OkHttpClient();
        String s = urlallerr + "?ak=IK5AlGXoZ23tDAGjldRalicbhdpsrKwE&service_id=135958&keyword=" + location + "&filter=status:" + stutas + "|cityNo:" + cityno + "&return_type=simple";
        Log.i("15641512342", s);
        final Request request = new Request.Builder()
                .url(s)
                .build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("15641512342", e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body().string();
                Log.i("15641512342", resp);
                final SingleBicycle singleBicycle = GsonTools.changeGsonToBean(resp, SingleBicycle.class);
                if (singleBicycle != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (singleBicycle.getStatus() == 0) {
                                switch (stutas) {
                                 /*（0：正常 1：使用中  2:离线 3:报废 4:升级 5：预约中 6:借车处理中 7：故障    8：低电量车 ）*/
                                    case "0":
                                        tvName.setText("正常车数量：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "2":
                                        tvLasttime.setText("离线车数量：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "7":
                                        tvSpeed.setText("故障车数量：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "8":
                                        tvCity.setText("低电量车数量：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "9":
                                        tvStutes.setText("僵尸车数量：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "10":
                                        mTvUnrechargeableBike.setText("不可充电车：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "11":
                                        tvRepairing.setText("维修中车数量："+singleBicycle.getTotal()+"辆");
                                        break;
                                    case "15":
                                        tvNeedback.setText("需召回车辆：" + singleBicycle.getTotal() + "辆");
                                        break;
                                    case "16":
                                        tvShutdown.setText("关机车：" + singleBicycle.getTotal() + "辆");
                                        break;
                                }
                            } else if (singleBicycle.getStatus() == 3003) {
                                switch (stutas) {
                                 /*（0：正常 1：使用中  2:离线 3:报废 4:升级 5：预约中 6:借车处理中 7：故障    8：低电量车 ）*/
                                    case "0":
                                        tvName.setText("正常车数量：0辆");
                                        break;
                                    case "2":
                                        tvLasttime.setText("离线车数量：0辆");
                                        break;
                                    case "7":
                                        tvSpeed.setText("故障车数量：0辆");
                                        break;
                                    case "8":
                                        tvCity.setText("低电量车数量：0辆");
                                        break;
                                    case "9":
                                        tvStutes.setText("僵尸车数量：0辆");
                                        break;
                                    case "10":
                                        mTvUnrechargeableBike.setText("不可充电车：0辆");
                                        break;
                                    case "11":
                                        tvRepairing.setText("维修中车数量：0辆");
                                        break;
                                    case "15":
                                        tvNeedback.setText("需召回车辆：0辆");
                                        break;
                                    case "16":
                                        tvShutdown.setText("关机车：0辆");
                                        break;
                                }
                            } else {
                                showToast("获取数据失败");
                            }

                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                        }
                    });
                }

            }
        });
    }


    /*判断区域是否大于3000平方千米*/
    public void IsOverArea(String point) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(urlall + "?ak=IK5AlGXoZ23tDAGjldRalicbhdpsrKwE&service_id=135958&vertexes=" + point + "&page_size=1")
                .build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body().string();
                Log.i("15641512", resp);
                final SingleBicycle singleBicycle = GsonTools.changeGsonToBean(resp, SingleBicycle.class);
                if (singleBicycle != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("33451154", "jinle" + singleBicycle.getStatus());
                            if (singleBicycle.getStatus() == 0) {
                                String cityNo = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "cityNo", ""));
                                Log.i("221211", "" + cityNo);
                                if (cityNo.equals("")) {
                                    showToast("请重新登录");
                                    return;
                                }
                                Log.i("33451154", "yy:" + singleBicycle.getStatus());
                                tvName.setText("查询中......");
                                tvStutes.setText("查询中......");
                                tvCity.setText("查询中......");
                                tvSpeed.setText("查询中......");
                                tvLasttime.setText("查询中......");
                                GetAllBicycle(newpointlist, "0", cityNo);
                                GetAllBicycle(newpointlist, "2", cityNo);
                                GetAllBicycle(newpointlist, "7", cityNo);
                                GetAllBicycle(newpointlist, "8", cityNo);
                                GetAllBicycle(newpointlist, "9", cityNo);
                                GetAllBicycle(newpointlist, "10", cityNo);
                                GetAllBicycle(newpointlist, "11", cityNo);
                                GetAllBicycle(newpointlist, "15", cityNo);
                                GetAllBicycle(newpointlist, "16", cityNo);
                            } else {
                                Log.i("33451154", "yy:" + singleBicycle.getStatus());
                                String areaName = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "AreaName", ""));
                                String cityNo = String.valueOf(SharedPreferencesUtils.getParam(SerchCar.this, "cityNo", ""));
                                if (cityNo.equals("")) {
                                    showToast("请重新登录");
                                    return;
                                }
                                Log.i("14411544", "tt:" + areaName);
                                GetAllBicycleErr("" + areaName, "0", cityNo);
                                GetAllBicycleErr("" + areaName, "2", cityNo);
                                GetAllBicycleErr("" + areaName, "7", cityNo);
                                GetAllBicycleErr("" + areaName, "8", cityNo);
                                GetAllBicycleErr("" + areaName, "9", cityNo);
                                GetAllBicycleErr("" + areaName, "10", cityNo);
                                GetAllBicycleErr("" + areaName, "11", cityNo);
                                GetAllBicycleErr("" + areaName, "15", cityNo);
                                GetAllBicycleErr("" + areaName, "16", cityNo);
                            }
                        }
                    });
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        map.onDestroy();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map.onSaveInstanceState(outState);
    }

    @Override
    protected void onResponseSuccess(Response response, String action) {

    }

    @Override
    protected void onResponseFailure(Throwable e, String action) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        map.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        map.onResume();

    }


    /*移动初始地图镜头*/
    private void resetLocation(double v1, double v2, int x) {
        LatLng latlon = new LatLng(v1, v2);
        map.getMap().animateCamera(CameraUpdateFactory.newLatLngZoom(latlon, x), 1000, null);

    }

    /*移动地图至显示边界*/
    private void resetnewLocation(List<LatLng> latLngs) {
        if (latLngs == null) {
            return;
        }
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (LatLng latLng : latLngs) {
            builder.include(latLng);
        }
        map.getMap().animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 1), 1000, null);

    }


    /*绘制地图点*/
    private void setMarker(double v1, double v2, BitmapDescriptor bitmap) {
        LatLng point = new LatLng(v1, v2);
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(point);
        markerOption.icon(bitmap);
        markerOption.setFlat(true);
        map.getMap().addMarker(markerOption);
    }

    /*绘制多边形*/
    public void setPolygon() {
        if (latLngs.isEmpty()) {
            return;
        }
        // 声明 多边形参数对象
        PolygonOptions polygonOptions = new PolygonOptions();
        polygonOptions.addAll(latLngs);
        polygonOptions.strokeWidth(15)
                .strokeColor(Color.argb(200, 250, 20, 60))
                .fillColor(Color.argb(0, 0, 0, 0));   // 多边形的填充色
        map.getMap().addPolygon(polygonOptions);
    }


}
